package com.syezon.wifikey.splash;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.WindowManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.syezon.wifikey.BuildConfig;
import com.syezon.wifikey.R;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.splash.config.SplashConfig;
import com.syezon.wifikey.splash.gdt.GdtSplashFragment;
import com.syezon.wifikey.splash.self.SelfSplashFragment;
import com.syezon.wifikey.splash.tt.TTSplashFragment;


import java.util.ArrayList;
import java.util.List;


public class FrontAdActivity extends BaseActivity implements SplashCallBack {

    private boolean canJump;
    private Handler mHandler = new Handler();
    private long mFetchSplashADTime;
    private static final long MAX_FRONT_LOAD_TIME = 4000;
    private List<String> mSplashAdOrderList = new ArrayList<>();
    private Runnable mCloseTask = new Runnable() {
        @Override
        public void run() {
            goMain();
        }
    };
    private int retryCount;

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return super.isApplyStatusBarTranslucency();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.app_splash_activity;
    }

    @Override
    protected void initViewsAndEvents() {
        nextStep();
    }

    private void nextStep() {
        mHandler.postDelayed(mCloseTask, MAX_FRONT_LOAD_TIME);
        String splashAdSource = SplashConfig.getSplashAdSource();
        mSplashAdOrderList = SplashConfig.getSplashAdOrderList();
        mFetchSplashADTime = System.currentTimeMillis();
        loadSplashAd(splashAdSource);
    }

    private void loadSplashAd(String splashAdCode) {
        if (SplashConfig.SPLASH_AD_SOURCE_GDT.equals(splashAdCode)) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, GdtSplashFragment.newInstance(GDTConfig.SplashPosID))
                    .commitAllowingStateLoss();
        } else if (SplashConfig.SPLASH_AD_SOURCE_TT.equals(splashAdCode)) {
//            TTAdManagerHolder.get().requestPermissionIfNecessary(this);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, TTSplashFragment.newInstance())
                    .commitAllowingStateLoss();
        } else if (SplashConfig.SPLASH_AD_SOURCE_SELF.equals(splashAdCode)) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, SelfSplashFragment.newInstance())
                    .commitAllowingStateLoss();
        } else {
            /**
             * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
             * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
             * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
             **/
            long alreadyDelayMills = System.currentTimeMillis() - mFetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
            long shouldDelayMills = alreadyDelayMills > MAX_FRONT_LOAD_TIME ? 0 : MAX_FRONT_LOAD_TIME
                    - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
            // 计算出还需要延时多久
            mHandler.postDelayed(mCloseTask, shouldDelayMills);
        }
    }


    @Override
    public void goMain() {
        finish();
    }

    @Override
    public void onLoadSuccess(String adSourceCode) {
        LogUtils.eTag("splash", "onLoadSuccess " + adSourceCode);
        mHandler.removeCallbacks(mCloseTask);
        SplashConfig.saveLastSplashAdCode(adSourceCode);
    }

    @Override
    public void onLoadFail(String adSourceCode, String errorMsg) {
        LogUtils.eTag("splash", "onLoadFail " + adSourceCode + " errorMsg " + errorMsg);
        String nextSplashAdCode = SplashConfig.getNextSplashAdCode(adSourceCode, mSplashAdOrderList, ++retryCount);
        if (BuildConfig.DEBUG) {
            ToastUtils.showShort(adSourceCode + "加载失败 重试" + nextSplashAdCode);
        }
        loadSplashAd(nextSplashAdCode);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
        if (canJump) {
            goMain();
        } else {
            canJump = true;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        super.onRestoreInstanceState(savedInstanceState);
    }

}
